package com.payment.system.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.payment.system.service.IMoneyChangeService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.payment.common.base.AjaxResult;
import com.payment.common.support.Convert;
import com.payment.common.type.LevelStatus;
import com.payment.common.type.PaymentOrderType;
import com.payment.common.type.PlanItemType;
import com.payment.common.type.SMSTemplateType;
import com.payment.common.utils.DateUtils;
import com.payment.common.utils.RedisPoolUtil;
import com.payment.common.utils.StringUtils;
import com.payment.common.utils.pay.EncryptUtil;
import com.payment.system.domain.Acq;
import com.payment.system.domain.IssBank;
import com.payment.system.domain.Merchant;
import com.payment.system.domain.MerchantIncreaseLimit;
import com.payment.system.domain.MerchantMonth;
import com.payment.system.domain.MerchantUpgrade;
import com.payment.system.domain.MerchantWallet;
import com.payment.system.domain.MoneyChange;
import com.payment.system.domain.PaymentOrder;
import com.payment.system.domain.PlanItemNew;
import com.payment.system.domain.PlanNew;
import com.payment.system.domain.SystemConfig;
import com.payment.system.mapper.AcqMapper;
import com.payment.system.mapper.IssBankMapper;
import com.payment.system.mapper.MerchantIncreaseLimitMapper;
import com.payment.system.mapper.MerchantMapper;
import com.payment.system.mapper.MerchantMonthMapper;
import com.payment.system.mapper.MerchantParentMapper;
import com.payment.system.mapper.MerchantUpgradeMapper;
import com.payment.system.mapper.MerchantWalletMapper;
import com.payment.system.mapper.MoneyChangeMapper;
import com.payment.system.mapper.PaymentOrderMapper;
import com.payment.system.mapper.PlanItemNewMapper;
import com.payment.system.mapper.PlanNewMapper;
import com.payment.system.mapper.SystemConfigMapper;
import com.payment.system.service.IAcqService;
import com.payment.system.service.IPaymentOrderService;
import com.payment.system.util.GuangGuUtil;
import com.payment.system.vo.EcharsVo;
import com.payment.system.vo.MonthVolumeVo;
import com.payment.system.vo.PaymentOrderVO;

import net.sf.json.JSONArray;

/**
 * 交易订单 服务层实现
 *
 * @author payment
 * @date 2019-02-17
 */
@Service
public class PaymentOrderServiceImpl implements IPaymentOrderService {

    private static final Logger logger = LoggerFactory.getLogger(PaymentOrderServiceImpl.class);

    @Autowired
    private WxAliPayServiceImpl wxAliPayService;
    @Autowired
    private PaymentOrderMapper paymentOrderMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MoneyChangeMapper moneyChangeMapper;
    @Autowired
    private MerchantMonthMapper merchantMonthMapper;
    @Autowired
    private PlanItemNewMapper planItemNewMapper;
    @Autowired
    private PlanNewMapper planNewMapper;
    @Autowired
    private AcqMapper acqMapper;
    @Autowired
    private IssBankMapper issBankMapper;
    @Autowired
    private SystemConfigMapper configMapper;
    @Autowired
    private MerchantIncreaseLimitMapper merchantIncreaseLimitMapper;
    @Autowired
    private IAcqService acqService;
    @Autowired
    private MerchantWalletMapper merchantWalletMapper;
    @Autowired
    private IMoneyChangeService moneyChangeService;
    @Autowired
    private MerchantParentMapper merchantParentMapper;
    @Autowired
    private MerchantUpgradeMapper merchantUpgradeMapper;

    /**
     * 查询交易订单信息
     *
     * @param id 交易订单ID
     * @return 交易订单信息
     */
    @Override
    public PaymentOrder selectPaymentOrderById(String id) {
        PaymentOrder paymentOrder = paymentOrderMapper.selectPaymentOrderById(id);
        if (paymentOrder != null) {
            paymentOrder.setCreditNumber(EncryptUtil.desEncryptMessage(paymentOrder.getCreditNumber()));
        }
        return paymentOrder;
    }

    /**
     * 查询交易订单列表 加密
     *
     * @param paymentOrder 交易订单信息
     * @return 交易订单集合
     */
    @Override
    public List<PaymentOrder> selectPaymentOrderList(PaymentOrder paymentOrder) {
        List<PaymentOrder> list = paymentOrderMapper.selectPaymentOrderList(paymentOrder);
        for (PaymentOrder paymentOrder1 : list) {
            if (StringUtils.isNotEmpty(paymentOrder1.getCreditNumber())) {
                paymentOrder1.setCreditNumber(EncryptUtil.desEncryptMessage(paymentOrder1.getCreditNumber()));
            }

        }
        return list;
    }

    /**
     * 查询交易订单列表 不加密
     *
     * @param paymentOrder 交易订单信息
     * @return 交易订单集合
     */
    @Override
    public List<PaymentOrder> selectPaymentOrderListNoEncrypt(PaymentOrder paymentOrder) {
        return paymentOrderMapper.selectPaymentOrderList(paymentOrder);
    }

    /**
     * 新增交易订单
     *
     * @param paymentOrder 交易订单信息
     * @return 结果
     */
    @Override
    public int insertPaymentOrder(PaymentOrder paymentOrder) {
        return paymentOrderMapper.insertPaymentOrder(paymentOrder);
    }

    /**
     * 修改交易订单
     *
     * @param paymentOrder 交易订单信息
     * @return 结果
     */
    @Override
    public int updatePaymentOrder(PaymentOrder paymentOrder) {
        return paymentOrderMapper.updatePaymentOrder(paymentOrder);
    }

    /**
     * 删除交易订单对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deletePaymentOrderByIds(String ids) {
        return paymentOrderMapper.deletePaymentOrderByIds(Convert.toStrArray(ids));
    }

    /**
     * //获取 获取月 还款交易量，收款月交易量，升级分享量
     *
     * @param merchantPhone
     * @param level
     * @return
     */
    @Override
    public AjaxResult selectMonthVolume(String merchantPhone, String level) {
        if (StringUtils.isEmpty(merchantPhone) || StringUtils.isEmpty(level)) {
            return AjaxResult.error(1, "缺失参数");
        }
        Integer le = Integer.parseInt(level);
        Integer count = merchantMapper.selectCustomerCount(merchantPhone, le - 1);
        Merchant merchant = merchantMapper.selectByPhone(merchantPhone);

        MonthVolumeVo volumeVo = new MonthVolumeVo();
        volumeVo.setLevel(merchant.getLevel().toString());
        volumeVo.setCount(count);// 直推总数
        volumeVo.setMerchantId(merchant.getId());
        volumeVo.setName(merchant.getMerchantCnName());
        volumeVo.setPhone(merchant.getPhone());
        // 获取月还款交易量，收款月交易量 月统计表
        MerchantMonth merchantMonth = merchantMonthMapper.selectMerchantDayByIdAndDate(merchant.getId(),
                DateUtils.getDate1());
        if (merchantMonth == null) {
            volumeVo.setHkMonth(new BigDecimal(0));
            volumeVo.setSkMonth(new BigDecimal(0));
        } else {
            volumeVo.setHkMonth(merchantMonth.getHkMoney() == null ? new BigDecimal(0) : merchantMonth.getHkMoney());
            volumeVo.setSkMonth(merchantMonth.getSkMoney() == null ? new BigDecimal(0) : merchantMonth.getSkMoney());
        }

        return AjaxResult.successAndData("获取用户信息成功", volumeVo);
    }

    @Override
    public PaymentOrder selectPaymentOrderByOrderNo(String settleNo) {
        // TODO Auto-generated method stub
        return paymentOrderMapper.selectPaymentOrderByOrderNo(settleNo);
    }

    //// 查询一周的交易总额和交易笔数
    @Override
    public List<EcharsVo> selectPaymentOrderByWeek(String agentId) {
        List<EcharsVo> list = new ArrayList<>();
        //获取当前时间前七天的日期
        ArrayList<String> pastDaysList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - i);
            Date monday = calendar.getTime();
            SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd");
            String result = format.format(monday);
            pastDaysList.add(result);
        }
        for (String a : pastDaysList) {
            EcharsVo echarsVo = paymentOrderMapper.selectPaymentOrderByWeek(agentId, a);
            echarsVo.setTradeTime(a);
            list.add(echarsVo);
        }

        return list;
    }

    /**
     * app 端交易明细：订单类型（0 无卡消费 1养卡消费 2养卡代付3无卡出款5提现 6充值升级）
     * 当月交易总额，当月交易笔数，
     *
     * @param merchantId 用户ID
     * @param pageNum    页数
     * @param pageSize   每页条数
     * @return
     */
    @Override
    public AjaxResult transactionDetailsList(String merchantId, Integer pageNum, Integer pageSize) {
        if (StringUtils.isEmpty(merchantId)) {
            return AjaxResult.error(1, "获取交易明细失败：缺失参数");
        }

        Map<String, Object> map = new HashMap<String, Object>(16);
        List<PaymentOrder> list = paymentOrderMapper.selectOrderListByApp(merchantId, pageNum * pageSize, pageSize);
        // 当月交易总额，当月交易笔数，
        //EcharsVo monthRecordMoney = paymentOrderMapper.selectMonthRecordByMerchantId(merchantId);
        // 交易
        //WithdrawMoneyVo monthRecordWithdrawMoney = moneyChangeMapper.selectMonthRecordWithdrawMoney(merchantId);
        MerchantWallet mw = merchantWalletMapper.selectMerchantWalletById(merchantId);
        if (mw == null) {
            //收款
            map.put("skMoney", 0);
            //养卡
            map.put("hkMoney", 0);
            //总
            map.put("totalMoney", 0);
        } else {
            //收款
            map.put("skMoney", mw.getSkMonth().setScale(3, BigDecimal.ROUND_DOWN));
            //养卡
            map.put("hkMoney", mw.getHkMonth().setScale(3, BigDecimal.ROUND_DOWN));
            //总
            map.put("totalMoney", mw.getSkMonth().add(mw.getHkMonth()).setScale(3, BigDecimal.ROUND_DOWN));
        }
        map.put("detailsList", list);
        return AjaxResult.successAndData("获取交易明细列表成功", map);
    }


    /**
     * 手动清分
     *
     * @return
     */
    @Override
    public AjaxResult manualClearing() {
        // 需要清分的订单类型：0无卡快捷，1养卡消费
        // 订单类型（0无卡快捷 1养卡消费）

        List<PaymentOrder> paymentOrderList = paymentOrderMapper.selectPaymentOrderListByClearingStatus(0);
        if (paymentOrderList.size() == 0) {
            return AjaxResult.success("暂无需要清分的订单");
        }
        for (PaymentOrder order : paymentOrderList) {
            Merchant merchant = merchantMapper.selectMerchantById(order.getMerchantId());
            //0 11  1 7
            if (order.getOrderType().equals(0) || order.getOrderType().equals(1) || order.getOrderType().equals(7) || order.getOrderType().equals(11)) {
                moneyChangeService.commissions(order.getId(), order.getOrderType(),
                        order.getAmountMoney(), order.getMerchantId(), order.getProfitMoney());
            } else if (order.getOrderType().equals(PaymentOrderType.TEN.getCode())) {
                //境外
                wxAliPayService.orderProfit(order, merchant.getPhone());
            }


        }
        return AjaxResult.success("手工清算成功!成功清算" + paymentOrderList.size() + "条数据!");
    }

    // 根据订单状态和 上游code查询
    @Override
    public List<PaymentOrder> selectPaymentOrderListByStatusAndAcqReturnCode(int status, String msg, String createTime) {
        return paymentOrderMapper.selectPaymentOrderListByStatusAndAcqReturnCode(status, msg, createTime);
    }

    //// 根据订单状态，通道返回码和返回信息成功
    @Override
    public List<PaymentOrder> selectPaymentOrderListByStatusAndAcqReturnCodeAndReturnMsg(int status, String acqCode,
                                                                                         String acqMsg) {

        return paymentOrderMapper.selectPaymentOrderListByStatusAndAcqReturnCodeAndReturnMsg(status, acqCode, acqMsg);
    }


    @Override
    public Map<String, Object> selectOrderTotalMoney(PaymentOrder paymentOrder) {

        return paymentOrderMapper.selectOrderTotalMoney(paymentOrder);
    }


    //查询用户最新的一条 无卡记录
    @Override
    public AjaxResult getNewestOrderWKByCreditCardIdId(String creditNumber) {
        if (StringUtils.isEmpty(creditNumber)) {
            return AjaxResult.error(1, "获取信息失败");
        }
        PaymentOrder order = paymentOrderMapper.getNewestOrderWKByCreditCardIdId(creditNumber);
        if (order == null) {
            return AjaxResult.success("成功");
        }
        if (DateUtils.compareDateByBranch(order.getCreateTime()) <= 30) {
            return AjaxResult.error(1, "短时间内不要频繁操作，以免对您的信用卡造成影响!");
        } else {
            return AjaxResult.success("成功");
        }

    }

    //无卡出款
    @Override
    public AjaxResult daiFuRepairOrderGGWK(String id) {
        PaymentOrder order = paymentOrderMapper.selectPaymentOrderById(id);
        if (order == null) {
            return AjaxResult.error(2, "获取订单信息失败");
        }
        //订单编号
        order.setOrderNo(StringUtils.createNum());
        //创建修改订单对象
        PaymentOrder p = new PaymentOrder();
        p.setId(order.getId());
        p.setOrderNo(order.getOrderNo());
        try {
            Merchant merchant = merchantMapper.selectMerchantById(order.getMerchantId());
            //查询钱包
            JSONObject jsonObject = GuangGuUtil.walletQuery(merchant);
            if ("SUCCESS".equals(jsonObject.getString("ret_code"))) {
                //查询账户余额
                if ("YQB000000".equals(jsonObject.getString("res_code"))) {
                    //转化上游返回信息
                    JSONArray jsonArr = JSONArray.fromObject(jsonObject.getString("wallet"));
                    for (int i = 0; i < jsonArr.size(); i++) {
                        //获取公司
                        String acqCode = jsonArr.getJSONObject(i).get("company_id").toString();
                        //获取余额
                        String balance = jsonArr.getJSONObject(i).get("balance").toString();
                        if (order.getAcqCode().equals(acqCode)) {
                            //判断余额
                            if (order.getAmountMoney().compareTo(new BigDecimal(balance)) == 1) {
                                return AjaxResult.error(1, "余额不足");
                            }
                        }
                    }
                }
            }
            PaymentOrderVO paymentOrderVO = wukaPayment(order, merchant);
            JSONObject json = GuangGuUtil.repayment(paymentOrderVO);
            //判断调用接口是否成功
            if ("SUCCESS".equals(json.getString("ret_code"))) {
                if ("YQB000000".equals(json.getString("res_code"))) {
                    //上游订单号
                    p.setAcqOrderNo(json.getString("seria_no"));
                    //上游订单状态
                    if ("1".equals(json.getString("status"))) {
                        //订单成功
                        //成功
                        p.setOrderStatus(1);
                        p.setAcqReturnCode(json.getString("res_code"));
                        p.setAcqReturnMsg(json.getString("res_msg"));
                    } else if ("2".equals(json.getString("status"))) {
                        //处理中
                        p.setOrderStatus(0);
                        p.setAcqReturnCode(json.getString("res_code"));
                        p.setAcqReturnMsg(json.getString("res_msg"));
                    } else {
                        //失败
                        p.setOrderStatus(2);
                        p.setAcqReturnMsg(json.getString("res_msg"));
                        p.setAcqReturnCode(json.getString("res_code"));
                    }
                    paymentOrderMapper.updatePaymentOrder(order);
                    return AjaxResult.success(json.getString("res_msg"));
                } else {
                    //失败更新订单信息
                    p.setOrderStatus(2);
                    p.setAcqReturnMsg(json.getString("res_msg"));
                    p.setAcqReturnCode(json.getString("res_code"));
                    paymentOrderMapper.updatePaymentOrder(order);
                    return AjaxResult.error(1, json.getString("res_msg"));
                }
            } else {
                //调用上游失败更新订单信息
                p.setOrderStatus(2);
                p.setAcqReturnCode(json.getString("res_code"));
                p.setAcqReturnMsg(json.getString("res_msg"));
                paymentOrderMapper.updatePaymentOrder(p);
                return AjaxResult.error(1, json.getString("ret_msg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            p.setOrderStatus(2);
            p.setAcqReturnCode("444");
            p.setAcqReturnMsg("出款异常：" + e.toString());
            paymentOrderMapper.updatePaymentOrder(p);
            return AjaxResult.error(1, "出款异常：" + e.toString());
        }
    }

    /**
     * 消费养卡退款
     *
     * @param id
     * @return
     */
    @Override
    public AjaxResult daiFuRepairOrderGG(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error(1, "获取订单编号失败");
        }
        PaymentOrder order = paymentOrderMapper.selectPaymentOrderById(id);
        if (order == null) {
            return AjaxResult.error(2, "获取订单信息失败");
        }
        order.setOrderStatus(3);
        paymentOrderMapper.updatePaymentOrder(order);
        //查询商户钱包余额
        BigDecimal moneyNow = order.getAmountMoney().subtract(order.getRateMoney());
        order.setAmountMoney(moneyNow);
        try {
            Merchant merchant = merchantMapper.selectMerchantById(order.getMerchantId());
            //查询钱包
            JSONObject jsonObject = GuangGuUtil.walletQuery(merchant);
            //查询账户余额
            if ("SUCCESS".equals(jsonObject.getString("ret_code"))) {
                if ("YQB000000".equals(jsonObject.getString("res_code"))) {
                    //转化上游返回信息
                    JSONArray jsonArr = JSONArray.fromObject(jsonObject.getString("wallet"));
                    for (int i = 0; i < jsonArr.size(); i++) {
                        //获取余额
                        String balance = jsonArr.getJSONObject(i).get("balance").toString();
                        //获取公司
                        String acqCode = jsonArr.getJSONObject(i).get("company_id").toString();
                        if (order.getAcqCode().equals(acqCode)) {
                            //判断余额
                            if (order.getAmountMoney().compareTo(new BigDecimal(balance)) == 1) {
                                return AjaxResult.error(1, "余额不足");
                            }
                        }
                    }
                }
            }
            //根据渠道id查询渠道信息
            Acq acq = acqMapper.selectAcqById(order.getAcqId());
            //查询小计划信息
            PlanItemNew planItemNew = planItemNewMapper.selectPlanItemNewListByOrderId(id);
            //查询大计划获取计划类型
            PlanNew planNew = new PlanNew();
            if (planItemNew != null) {
                planNew = planNewMapper.selectPlanNewById(planItemNew.getPlanId());
                //修改大计划状态
                planNew.setStatus(5);
                planNewMapper.updatePlanNew(planNew);
            }
            //生成退款订单
            order.setId(StringUtils.randomUUID());
            //订单号
            order.setOrderNo(StringUtils.createNum());
            //订单状态
            order.setOrderStatus(0);
            //订单类型 退款
            order.setOrderType(4);
            //成本手续费
            order.setCostRateMoney(acq.getDrawRate());
            //实际手续费
            order.setRateMoney(new BigDecimal(planNew.getPro()));
            //收益
            order.setProfitMoney(new BigDecimal(planNew.getPro()).subtract(acq.getDrawRate()));
            //是否回调
            order.setIsNotify(0);
            //创建时间
            order.setCreateTime(new Date());
            paymentOrderMapper.insertPaymentOrder(order);
            PaymentOrderVO paymentOrderVO = ykPayment(order, merchant, planNew);
            //创建修改订单对象
            PaymentOrder updata = new PaymentOrder();
            updata.setId(order.getId());
            //调用上游接口
            JSONObject json = GuangGuUtil.repayment(paymentOrderVO);
            if ("SUCCESS".equals(json.getString("ret_code"))) {
                if ("YQB000000".equals(json.getString("res_code"))) {
                    //上游订单号
                    updata.setAcqOrderNo(json.getString("seria_no"));
                    //订单状态
                    if ("1".equals(json.getString("status"))) {
                        //成功
                        updata.setAcqReturnCode(json.getString("res_code"));
                        updata.setAcqReturnMsg(json.getString("res_msg"));
                        updata.setOrderStatus(1);
                    } else if ("2".equals(json.getString("status"))) {
                        //处理中
                        updata.setAcqReturnCode(json.getString("res_code"));
                        updata.setAcqReturnMsg(json.getString("res_msg"));
                        updata.setOrderStatus(0);
                    } else {
                        //失败
                        updata.setOrderStatus(2);
                        updata.setAcqReturnCode(json.getString("res_code"));
                        updata.setAcqReturnMsg(json.getString("res_msg"));
                    }
                    paymentOrderMapper.updatePaymentOrder(updata);
                    return AjaxResult.success(json.getString("res_msg"));
                } else {
                    //失败
                    updata.setAcqReturnCode(json.getString("res_code"));
                    updata.setAcqReturnMsg(json.getString("res_msg"));
                    updata.setOrderStatus(2);
                    paymentOrderMapper.updatePaymentOrder(updata);
                    return AjaxResult.error(1, json.getString("res_msg"));
                }
            } else {
                //调用上游失败
                updata.setAcqReturnCode(json.getString("res_code"));
                updata.setAcqReturnMsg(json.getString("res_msg"));
                updata.setOrderStatus(2);
                paymentOrderMapper.updatePaymentOrder(updata);
                return AjaxResult.error(1, "出款失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(1, "出款异常：" + e.toString());
        }
    }

    /**
     * 养卡消费退款封装参数
     *
     * @param order
     * @param merchant
     * @param planNew
     * @return
     */
    private PaymentOrderVO ykPayment(PaymentOrder order, Merchant merchant, PlanNew planNew) {
        //封装参数
        PaymentOrderVO pa = new PaymentOrderVO();
        //0 无卡 1养卡
        pa.setPaymentType(1);
        //公司id
        pa.setAcqCode(order.getAcqCode());
        //订单号
        pa.setOrderNo(order.getOrderNo());
        //用户id
        pa.setUserId(merchant.getAcqMerchantNo());
        //账户名称
        pa.setBankAccountName(order.getMerchantName());
        //银行卡号
        pa.setCreditNumber(order.getCreditNumber());
        //银行名称
        pa.setBankName(order.getBankName());
        //根据银行卡名称查询
        IssBank issBank = issBankMapper.selectIssBankByName(order.getBankName());
        //银行卡代码
        pa.setBankCode(issBank.getBankCode());
        //证件号
        pa.setIdCardNo(merchant.getIdCardNumber());
        //根据卡号查询信用卡信息
        MerchantIncreaseLimit merchantIncreaseLimit = merchantIncreaseLimitMapper.selectByBankAccount(order.getCreditNumber());
        //手机号
        pa.setMobile(merchantIncreaseLimit.getBankPhone());
        //信用卡cvn
        pa.setMccCode(merchantIncreaseLimit.getCvn());
        //信用卡有效期
        pa.setExpired(merchantIncreaseLimit.getExpdate());
        //金额
        pa.setAmountMoney(order.getAmountMoney());
        //笔数费
        pa.setPro(order.getRateMoney());
        //ip
        pa.setTrxSourceIp(order.getIp());
        //费率
        pa.setRate(planNew.getRate());
        //个人账户
        pa.setBankType("1");
        //贷记卡
        pa.setCardType("2");
        return pa;
    }

    /**
     * 无卡出款封装调用三方参数
     *
     * @param order
     */
    private PaymentOrderVO wukaPayment(PaymentOrder order, Merchant merchant) {
        PaymentOrderVO pa = new PaymentOrderVO();
        //0 无卡 1养卡
        pa.setPaymentType(0);
        //公司id
        pa.setAcqCode(order.getAcqCode());
        //订单号
        pa.setOrderNo(order.getOrderNo());
        //用户id
        pa.setUserId(merchant.getAcqMerchantNo());
        //账户名称
        pa.setBankAccountName(merchant.getMerchantCnName());
        //银行卡号
        pa.setCreditNumber(merchant.getBankAccount());
        //银行卡代码
        pa.setBankCode(merchant.getBankCode());
        //银行名称
        pa.setBankName(merchant.getBankName());
        //证件号
        pa.setIdCardNo(merchant.getIdCardNumber());
        //手机号
        pa.setMobile(merchant.getReservePhone());
        //金额
        pa.setAmountMoney(order.getAmountMoney());
        //笔数费
        pa.setPro(order.getRateMoney());
        //ip
        pa.setTrxSourceIp(order.getIp());
        //费率
        pa.setRate("0");
        //个人账户
        pa.setBankType("1");
        //借记卡
        pa.setCardType("1");
        return pa;
    }

    /**
     * 查询订单
     *
     * @param id
     * @return
     */
    @Override
    public AjaxResult findOrderGG(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error(1, "缺失订单号");
        }
        PaymentOrder order = paymentOrderMapper.selectPaymentOrderById(id);
        if (order == null) {
            return AjaxResult.error(2, "获取订单信息失败");
        }
        if (order.getOrderStatus() == 1) {
            return AjaxResult.success("订单成功");
        }
        //根据商户id查询商户信息
        Merchant merchant = merchantMapper.selectMerchantById(order.getMerchantId());
        //调用三方查询传参对象
        PaymentOrderVO pa = new PaymentOrderVO();
        pa.setUserId(merchant.getAcqMerchantNo());
        pa.setOrderNo(order.getOrderNo());
        JSONObject json = null;
        try {
            //修改订单对象
            PaymentOrder p = new PaymentOrder();
            p.setId(order.getId());
            //已回调
            p.setIsNotify(1);
            //修改对象
            PlanItemNew planItemNewNow = new PlanItemNew();
            PlanNew planNewNow = new PlanNew();
            PlanItemNew planItemNew = new PlanItemNew();
            PlanNew planNew = new PlanNew();
            if (order.getOrderType() == 1 || order.getOrderType() == 2 || order.getOrderType() == 7 || order.getOrderType() == 8) {
                planItemNew = planItemNewMapper.selectPlanItemNewListByOrderId(order.getId());
                if (planItemNew != null) {
                    planItemNewNow.setId(planItemNew.getId());
                    planNew = planNewMapper.selectPlanNewById(planItemNew.getPlanId());
                    planNewNow.setId(planNew.getId());
                }
            }
            //判断订单类型
            if (order.getOrderType() == 1 || order.getOrderType() == 0 || order.getOrderType() == 7) {
                //调用三方消费查询
                json = GuangGuUtil.merchantConsumeQuery(pa);
                if ("SUCCESS".equals(json.getString("ret_code")) && "YQB000000".equals(json.getString("res_code"))) {
                    //调用三方成功,判断返回订单状态
                    if ("1".equals(json.getString("status"))) {
                        //订单成功
                        if ((order.getOrderType() == 1 || order.getOrderType() == 7) && planItemNew != null) {
                            //如果是养卡消费订单
                            //修改计划信息
                            planItemNewNow.setStatus(3);
                            planItemNewNow.setUpdateTime(new Date());
                            planItemNewMapper.updatePlanItemNew(planItemNewNow);
                        }
                        //修改订单状态
                        p.setOrderStatus(1);
                        if (order.getCompleteTime() == null) {
                            p.setCompleteTime(new Date());
                        }
                        //判断该笔订单是否已经分润
                        if (order.getClearingStatus() == 0) {
                            //计算分润
                            // moneyChangeService.commissions(order.getId(), order.getOrderType(), order.getAmountMoney(), order.getMerchantId());
                        }
                        //生成出款订单
                        if (order.getOrderType() == 0) {
                            //无卡消费返回值
                            Map<String, String> map = acqService.htguangGuOut(order, order.getMerchantId());
                            p.setAcqReturnCode(map.get("code"));
                            p.setAcqReturnMsg(map.get("msg"));
                            paymentOrderMapper.updatePaymentOrder(p);
                            return AjaxResult.success(map.get("msg"));
                        } else {
                            //养卡消费返回值
                            p.setAcqReturnCode(json.getString("res_code"));
                            p.setAcqReturnMsg(json.getString("res_msg"));
                            paymentOrderMapper.updatePaymentOrder(p);
                            return AjaxResult.success(json.getString("res_msg"));
                        }
                    }
                    if ("3".equals(json.getString("status"))) {
                        //订单失败
                        if (order.getOrderType() == 1 && planItemNew != null) {
                            //如果是养卡消费,修改计划状态
                            planItemNewNow.setStatus(2);
                            planNewNow.setStatus(2);
                            planItemNewNow.setUpdateTime(new Date());
                            planNewNow.setUpdateTime(new Date());
                            planNewMapper.updatePlanNew(planNewNow);
                            planItemNewMapper.updatePlanItemNew(planItemNewNow);
                        }
                        //修改订单状态
                        p.setOrderStatus(2);
                        p.setAcqReturnCode(json.getString("res_code"));
                        p.setAcqReturnMsg(json.getString("res_msg"));
                        paymentOrderMapper.updatePaymentOrder(p);
                        return AjaxResult.success(json.getString("res_msg"));
                    }
                    p.setAcqReturnCode(json.getString("res_code"));
                    p.setAcqReturnMsg(json.getString("res_msg"));
                    paymentOrderMapper.updatePaymentOrder(p);
                    return AjaxResult.success(json.getString("res_msg"));
                } else {
                    //调用上游失
                    p.setAcqReturnCode(json.getString("res_code"));
                    p.setAcqReturnMsg(json.getString("res_msg"));
                    paymentOrderMapper.updatePaymentOrder(p);
                    return AjaxResult.error(1, json.getString("res_msg"));
                }
                //订单类型（0 无卡消费 1养卡消费 2养卡代付3无卡出款4退款5提现 6充值升级）
            } else if (order.getOrderType() == 2 || order.getOrderType() == 3 || order.getOrderType() == 4 || order.getOrderType() == 8) {
                //调用三方还款提现查询
                json = GuangGuUtil.withdrawQuery(pa);
                if ("SUCCESS".equals(json.getString("ret_code")) && "YQB000000".equals(json.getString("res_code"))) {
                    //调用三方接口成功,判断返回状态
                    if ("1".equals(json.getString("status"))) {
                        //订单成功
                        if ((order.getOrderType() == 2 || order.getOrderType() == 8) && planItemNew != null) {
                            //订单类型为养卡代付,修改计划状态
                            planItemNewNow.setStatus(3);
                            planItemNewNow.setUpdateTime(new Date());
                            planItemNewMapper.updatePlanItemNew(planItemNewNow);
                            if (planItemNew.getGroupNumber().equals(planNew.getMaxGroupNum()) && PlanItemType.PAYMENT.getCode().equals(planItemNew.getMoneyType())) {
                                //判断数是否是最后一条
                                planNewNow.setUpdateTime(new Date());
                                planNewNow.setStatus(3);
                                planNewMapper.updatePlanNew(planNewNow);
                                Map<String, String> map = new HashMap<>(3);
                                map.put("user_phone", merchant.getReservePhone());
                                // 发送内容
                                String number = order.getCreditNumber();
                                number = number.substring(number.length() - 4, number.length());
                                String context = "你尾号为:" + number + "的银行卡本期计划已完成请您知悉。";
                                map.put("content", context);
                                map.put("sendType", SMSTemplateType.NOTICE.getCode());
                                if (order.getIsNotify() == 0) {
                                    JSONObject gg = GuangGuUtil.smsPackage(map);
                                    String resCode = gg.getString("res_code");
                                    if (("YQB000000").equals(resCode)) {
                                        logger.info("【主动查询订单】查询订单短信通知计划完成发送成功！");
                                    } else {
                                        logger.info("【主动查询订单】查询订单短信通知计划完成发送失败！");
                                    }
                                }
                            }
                        }
                        //修改订单状态
                        p.setOrderStatus(1);
                        if (order.getCompleteTime() == null) {
                            p.setCompleteTime(new Date());
                        }
                        p.setAcqReturnCode(json.getString("res_code"));
                        p.setAcqReturnMsg(json.getString("res_msg"));
                        paymentOrderMapper.updatePaymentOrder(p);
                        return AjaxResult.success(json.getString("res_msg"));
                    }
                    if ("3".equals(json.getString("status"))) {
                        //失败
                        if (order.getOrderType() == 2 && planItemNew != null) {
                            //订单类型为养卡代付,修改计划状态
                            planNewNow.setUpdateTime(new Date());
                            planItemNewNow.setUpdateTime(new Date());
                            planItemNewNow.setStatus(2);
                            planNewNow.setStatus(2);
                            planNewMapper.updatePlanNew(planNewNow);
                            planItemNewMapper.updatePlanItemNew(planItemNewNow);
                        }
                        p.setOrderStatus(2);
                        p.setAcqReturnCode(json.getString("res_code"));
                        p.setAcqReturnMsg(json.getString("res_msg"));
                        paymentOrderMapper.updatePaymentOrder(p);
                        return AjaxResult.success(json.getString("res_msg"));
                    }
                    p.setAcqReturnCode(json.getString("res_code"));
                    p.setAcqReturnMsg(json.getString("res_msg"));
                    paymentOrderMapper.updatePaymentOrder(p);
                    return AjaxResult.success(json.getString("res_msg"));
                } else {
                    //调用上游失败
                    p.setAcqReturnCode(json.getString("res_code"));
                    p.setAcqReturnMsg(json.getString("res_msg"));
                    paymentOrderMapper.updatePaymentOrder(p);
                    return AjaxResult.error(1, json.getString("res_msg"));
                }
            } else if (order.getOrderType() == 5) {
                //提现订单
                json = GuangGuUtil.withdrawQuery(pa);
                if ("SUCCESS".equals(json.getString("ret_code")) && "YQB000000".equals(json.getString("res_code"))) {
                    p.setAcqReturnCode(json.getString("res_code"));
                    p.setAcqReturnMsg(json.getString("res_msg"));
                    //调用三方接口成功,判断返回状态 1成功 2:处理中 3:失败
                    if ("1".equals(json.getString("status"))) {
                        p.setCompleteTime(new Date());
                        p.setOrderStatus(1);
                        paymentOrderMapper.updatePaymentOrder(p);
                        List<MoneyChange> moneyChangeList = moneyChangeMapper.selectMoneyChangeListByOrderId(p.getId());
                        if (moneyChangeList == null || moneyChangeList.size() == 0) {
                            return AjaxResult.error("获取提现信息失败，请联系相关技术人员");
                        }
                        MoneyChange moneyChange = moneyChangeList.get(0);
                        moneyChange.setStatus("10C");
                        moneyChangeMapper.updateMoneyChange(moneyChange);
                        merchantWalletMapper.withdrawalSuccess(order.getMerchantId(), order.getAmountMoney());
                        return AjaxResult.success(json.getString("res_msg"));
                    } else if ("2".equals(json.getString("status"))) {
                        return AjaxResult.success("上游订单处理中");
                    } else {
                        p.setOrderStatus(2);
                        paymentOrderMapper.updatePaymentOrder(p);
                        //修改分润状态
                        List<MoneyChange> moneyChangeList = moneyChangeMapper.selectMoneyChangeListByOrderId(p.getId());
                        if (moneyChangeList == null || moneyChangeList.size() == 0) {
                            return AjaxResult.error("获取提现信息失败，请联系相关技术人员");
                        }
                        MoneyChange moneyChange = moneyChangeList.get(0);
                        moneyChange.setStatus("10D");
                        moneyChangeMapper.updateMoneyChange(moneyChange);
                        merchantWalletMapper.withdrawalFail(order.getMerchantId(), order.getAmountMoney());
                        return AjaxResult.error(json.getString("res_msg"));
                    }
                }

            }
        } catch (Exception e) {
            logger.error("查询订单异常{}", e);
        }
        return AjaxResult.error();
    }

    /**
     * 导入合伙人订单
     */
    @Override
    public AjaxResult uploadPartnerOrder(MultipartFile file) {

        if (file == null) {
            return AjaxResult.error("获取参数失败");
        }
        //初始化订单计划
        List<PaymentOrder> orderList = new ArrayList<PaymentOrder>();
        List<Workbook> workbookList = new ArrayList<>();
        try {
            workbookList.add(WorkbookFactory.create(file.getInputStream()));
        } catch (IOException e) {
            logger.error(e.toString());
            return AjaxResult.error("导入异常");
        } catch (InvalidFormatException e) {
            logger.error(e.toString());
            return AjaxResult.error("导入异常");
        }
        for (Workbook workbook : workbookList) {
            //有多少个sheet
            int sheets = workbook.getNumberOfSheets();
            for (int i = 0; i < sheets; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                //获取多少行
                int rows = sheet.getPhysicalNumberOfRows();
                PaymentOrder order = null;
                //遍历每一行，注意：第 0 行为标题
                for (int j = 1; j < rows; j++) {
                    try {
                        order = new PaymentOrder();
                        //获得第 j 行
                        Row row = sheet.getRow(j);
                        Row title = sheet.getRow(0); //获取标题
                        for (int l = 0; l < title.getPhysicalNumberOfCells(); l++) {
                            if (title.getCell(l).getStringCellValue().trim().equals("订单时间")) {
                                if (row.getCell(l) != null && row.getCell(l).getStringCellValue().length() <= 32) {
                                    Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, row.getCell(l).getStringCellValue());
                                    order.setCreateTime(date);
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("用户名称")) {
                                if (row.getCell(l) != null) {
                                    order.setMerchantName((row.getCell(l).getStringCellValue()));
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("交易金额")) {
                                if (row.getCell(l) != null) {
                                    row.getCell(l).setCellType(CellType.STRING);
                                    String amountMoney = row.getCell(l).getStringCellValue();
                                    order.setAmountMoney(new BigDecimal(amountMoney));
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("用户手机号")) {
                                if (row.getCell(l) != null) {
                                    row.getCell(l).setCellType(CellType.STRING);
                                    //返回提示信息保存用户手机号
                                    order.setAcqReturnMsg(row.getCell(l).getStringCellValue());
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("合伙人手机号")) {
                                if (row.getCell(l) != null) {
                                    //返回提示信息保存 推广人手机号
                                    row.getCell(l).setCellType(CellType.STRING);
                                    order.setAcqReturnCode(row.getCell(l).getStringCellValue());
                                }
                            } else if (title.getCell(l).getStringCellValue().trim().equals("支付方式")) {
                                if (row.getCell(l) != null) {
                                    if ("支付宝".equals(row.getCell(l).getStringCellValue())) {
                                        order.setAcqCode("2");
                                        order.setAcqId("2");
                                        order.setAcqName("支付宝");
                                    } else if ("微信".equals(row.getCell(l).getStringCellValue())) {
                                        order.setAcqCode("1");
                                        order.setAcqId("1");
                                        order.setAcqName("微信");
                                    }
                                }
                            } else {
                                continue;
                            }
                        }
                        orderList.add(order);
                    } catch (Exception e) {
                        logger.error("导入异常==={}", e);
                        return AjaxResult.error(e.toString());
                    }
                }
            }
        }
        if (orderList != null && orderList.size() > 0) {
            logger.info("合伙人订单导入{}", JSONObject.toJSONString(orderList));
            StringBuilder msg = new StringBuilder();
            //保存订单开始分润
            for (PaymentOrder order : orderList) {
                Merchant merchant = merchantMapper.selectMerchantByPhone(order.getAcqReturnMsg());
                if (merchant == null) {
                    msg.append(order.getAcqReturnMsg() + "用户不存在，");
                    continue;
                }
                //初始化线下订单信息
                order.setId(StringUtils.randomUUID());
                order.setOrderStatus(0);
                order.setCostRateMoney(new BigDecimal("0"));
                order.setRateMoney(new BigDecimal("0"));
                order.setProfitMoney(new BigDecimal("0"));
                order.setClearingStatus(1);
                order.setCreditNumber(merchant.getBankAccount());
                order.setBankName(merchant.getBankName());
                order.setOrderType(PaymentOrderType.SIX_H.getCode());
                order.setOrderNo(StringUtils.createNum());
                order.setOrderStatus(1);
                order.setCompleteTime(new Date());
                order.setMerchantId(merchant.getId());
                List<PaymentOrder> orderListVip = paymentOrderMapper.selectPaymentOrderListByMerchantIdAndStatus(merchant.getId(), 1,
                        PaymentOrderType.SIX_H.getCode());
                if (orderListVip != null && orderListVip.size() > 0) {
                    msg.append(order.getAcqReturnMsg() + "已升级过合伙人，");
                    continue;
                }
                List<MoneyChange> moneyChangeList = moneyChangeMapper.selectMoneyChangeListByOrderId(order.getId());
                if (moneyChangeList.size() > 0) {
                    msg.append(order.getAcqReturnMsg() + "重复分润，");
                    continue;
                }
                Merchant parentUser = merchantMapper.selectMerchantByPhone(order.getAcqReturnCode());
                if (parentUser == null) {
                    msg.append(order.getAcqReturnMsg() + "推荐人手机号不存在，");
                    continue;
                }
                Integer parentNum = merchantParentMapper.selectCongZhiNumByLevelAndParentPhone(parentUser.getPhone(),6);
                if (parentUser.getLevel().compareTo(6)>=0){
                	// 如果推荐人也是合伙人去看他是否够资格解冻金额或者手动的调整成自动升级的
                	if (parentUser.getIsCompany().equals("10D") && parentNum>=10){
                		saveMerchantUpgrade(parentUser.getId(), 6, "10E");
                	}
                	MerchantWallet pmw = merchantWalletMapper.selectMerchantWalletByMerId(parentUser.getId());
                	if (pmw.getPartnerMoney().compareTo(BigDecimal.valueOf(2000))==0 && parentNum >= 10){
                		MerchantWallet nowPmw = new MerchantWallet();
                		nowPmw.setId(pmw.getId());
                		nowPmw.setPartnerMoney(BigDecimal.ZERO);
                		nowPmw.setReleasePartnerMoney(BigDecimal.valueOf(2000));
                		nowPmw.setTotalMoney(pmw.getTotalMoney().add(BigDecimal.valueOf(2000)));
                		nowPmw.setBalanceMoney(pmw.getBalanceMoney().add(BigDecimal.valueOf(2000)));
                		nowPmw.setProfit(pmw.getProfit().add(BigDecimal.valueOf(2000)));
                		nowPmw.setProfitMoth(pmw.getProfitMoth().add(BigDecimal.valueOf(2000)));
                		merchantWalletMapper.updateMerchantWallet(nowPmw);
                		MoneyChange m = new MoneyChange();
                        m.setCreateTime(new Date());
                        m.setId(StringUtils.randomUUID());
                        m.setMoneyType("10Z");
                        m.setPaymentOrderId(order.getId());
                        m.setStatus("10C");
                        m.setUserId(parentUser.getId());
                        m.setTrxAmt(BigDecimal.valueOf(2000));
                        moneyChangeMapper.insertMoneyChange(m);
                	}
                } else {
                	// 如果推荐人不是合伙人去看他是否满足升级条件
                	if (parentNum>=10) {
                		 saveMerchantUpgrade(parentUser.getId(), 6, "10E");
                	}
                }
                String commission = "";
                try {
                    commission = RedisPoolUtil.get("commission");
                } catch (Exception e) {
                    commission = "nil";
                }
                if (commission == null || "nil".equals(commission) || "".equals(commission)) {
                    SystemConfig config = configMapper.selectSystemConfigByConfigCode("commission");
                    RedisPoolUtil.setex("commission", config.getConfigValue(), 86400);
                    commission = config.getConfigValue();
                }
                JSONObject jsonConfig = JSONObject.parseObject(commission);
                paymentOrderMapper.insertPaymentOrder(order);
                // 保存升级记录
                saveMerchantUpgrade(order.getMerchantId(), 6, "10C");
                //充值升级的合伙人添加冻结金额
                merchantWalletMapper.increasePartnerMoney(merchant.getId(), BigDecimal.valueOf(2000));
                //分润
                wxAliPayService.partnerCommission(order.getAcqReturnCode(), order.getId(), 
                		jsonConfig, order.getAmountMoney());

            }
            if (StringUtils.isNotEmpty(msg)) {
                return AjaxResult.error(msg.toString());
            }
            return AjaxResult.success();
        }

        return AjaxResult.error("重复上送");
    }
    
    void saveMerchantUpgrade(String merchantId,Integer level,String upType){
    	Merchant merchant = new Merchant();
    	merchant.setLevel(level);
    	merchant.setIsCompany(upType);
    	merchantMapper.updateMerchant(merchant);
		MerchantUpgrade merchantUpgrade = new MerchantUpgrade();
		merchantUpgrade.setId(StringUtils.randomUUID());
		merchantUpgrade.setPhone(merchant.getPhone());
		merchantUpgrade.setLevel(level);
		merchantUpgrade.setCreateTime(new Date());
		merchantUpgrade.setMerchantName(merchant.getMerchantCnName());
		merchantUpgrade.setType("10B");
		merchantUpgrade.setMerchantId(merchant.getId());
		merchantUpgradeMapper.insertMerchantUpgrade(merchantUpgrade);
    }
    
}
